package com.xukai.springboot.service;

import com.xukai.springboot.datalayer.patient.PatientMapper;
import com.xukai.springboot.datalayer.user.UserMapper;
import com.xukai.springboot.entity.response.account.AccountResponse;
import com.xukai.springboot.entity.response.account.WXAccountResponse;
import com.xukai.springboot.entity.sys.t_sys_user;
import com.xukai.springboot.service.patient.PatientWechatService;
import com.xukai.springboot.util.config.DatabaseContextHolder;
import com.xukai.springboot.util.constants.DataBaseType;
import com.xukai.springboot.util.wx.GetUserInfoResult;
import com.xukai.springboot.util.wx.WxAccessTokenResult;
import com.xukai.springboot.util.wx.WxOauthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class AccountService {

    /**
     * 应用唯一标识
     */
    @Value("${wxAppID}")
    private String wxAppID;

    /**
     * 应用密钥
     */
    @Value("${wxAppSecret}")
    private String wxAppSecret;

    /**
     * 日志
     */
    private final Logger logger = LoggerFactory.getLogger(AccountService.class);

    /**
     *
     */
    @Autowired
    private PatientMapper patientMapper;

    /**
     *
     */
    @Autowired
    private PatientWechatService patientWechatService;


    /**
     * 用户mapper
     */
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     */
    public WXAccountResponse WXAccount(String code) throws IOException {

        WXAccountResponse result = null;
        try {
            WxOauthUtil wxOauthUtil = WxOauthUtil.GetInstance(this.wxAppID, this.wxAppSecret);
            //获取微信access_token
            WxAccessTokenResult Access_Token = wxOauthUtil.Access_Token(code);
            if (Access_Token.getErrcode() != 0) {
                logger.error("WXAccount", Access_Token.getErrmsg());
                return null;
            }
            //获取微信用户信息
            GetUserInfoResult wxInfo = wxOauthUtil.GetUserInfor(Access_Token.getAccess_token(), Access_Token.getOpenid());
            if (wxInfo.getErrcode() != 0) {
                logger.error("WXAccount", wxInfo.getErrmsg());
                return null;
            }
            //获取本地用户信息
            result = patientMapper.WXAccount(Access_Token.getOpenid());
            if (result == null) {
                patientWechatService.CreatePatientWechat(wxInfo.getOpenid(), wxInfo.getNickname(), wxInfo.getProvince(), wxInfo.getSex(),
                        wxInfo.getCity(), wxInfo.getCountry(), wxInfo.getHeadimgurl(), wxInfo.getUnionid());
            } else {
                //判断数据是否有变更
                if (result.getHeadimg() != wxInfo.getHeadimgurl() || result.getSex() != wxInfo.getSex() || result.getWxNickName() != wxInfo.getNickname()) {
                    patientWechatService.UpdatePatientWechat(wxInfo.getOpenid(), wxInfo.getNickname(), wxInfo.getSex(), wxInfo.getProvince(), wxInfo.getCity(),
                            wxInfo.getCountry(), wxInfo.getHeadimgurl());
                    result.setWxNickName(wxInfo.getNickname());
                    result.setSex(wxInfo.getSex());
                    result.setHeadimg(wxInfo.getHeadimgurl());
                }
            }

        } catch (Exception ex) {
            throw ex;
        }

        return result;
    }


    /**
     * 服务端用户登录
     */
    public AccountResponse Account(String loginName, String passWord) {

        AccountResponse result = new AccountResponse();
        try {
            DatabaseContextHolder.setDB(DataBaseType.manager.name());
            t_sys_user data = userMapper.Account(loginName, passWord);

            if (data == null) {
                return null;
            }
            result.setContact(data.getContact());
            result.setDescribe(data.getDescribe());
            result.setEmail(data.getEmail());
            result.setIco(data.getIco());
            result.setLoginName(data.getLoginName());
            result.setId(data.getId());
            result.setState(data.getState());
            result.setUsername(data.getUsername());
            result.setWxCode(data.getWxCode());
        } catch (Exception ex) {
            throw ex;
        }

        return result;
    }


}
